﻿using PhotoGallery.Models;
using PhotoGallery.Models.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Helpers;
using System.Web.Hosting;
using System.Web.Mvc;
using PagedList;
using System.IO;
using PhotoGallery.Models.Utils;

namespace PhotoGallery.Controllers
{
    [Authorize]
    public class AudioController : BaseController
    {
        public ActionResult Index(int? albumID)
        {
            return RedirectToAction("List");
        }

        public ActionResult Details(int? id, int? albumID)
        {
            if (albumID == null)
            {
                return RedirectToAction("Index", "Albums");
            }
            if (!id.HasValue)
            {
                return RedirectToAction("Index");
            }

            AudioModel model = new AudioModel(albumID ?? default(int));
            return View(model.Get(id ?? default(int)));
        }

        public ActionResult Create()
        {
            if (Request.UrlReferrer != null)
            {
                TempData["backUrl"] = Request.UrlReferrer.ToString();
                ViewBag.backUrl = Request.UrlReferrer.ToString();
            }
            else
            {
                ViewBag.backUrl = Url.Action("Index");
            }
            return View(new AudioInfo());
        }

        [HttpPost]
        public ActionResult Create(AudioInfo audio, int albumID, HttpPostedFileBase[] files, HttpPostedFileBase thummnail)
        {
            ViewBag.backUrl = TempData["backUrl"];
            TempData.Keep();
            if (files.FirstOrDefault() != null)
            {
                if (ModelState.IsValid)
                {
                    AudioModel model = new AudioModel(albumID);
                    foreach (HttpPostedFileBase file in files)
                    {
                        if (FileValidation.IsValid(file, new List<string>(){
                            ".aac", ".m4v", ".m4a", ".mp1", ".mp2", ".mp3", ".mpg", ".mpeg", ".oga", ".ogg", ".wav", ".webm"
                        }))
                        {
                            model.Create(audio, file, thummnail);
                        }
                    }
                    return RedirectToAction("List");
                }
            }
            else
            {
                ModelState.AddModelError("", ErrorMessages.noFiles);
            }

            return View(audio);
        }

        public ActionResult Edit(int? id, int? albumID)
        {
            if (albumID == null)
            {
                return RedirectToAction("Index", "Albums");
            }
            if (!id.HasValue)
            {
                return RedirectToAction("Index");
            }

            if (Request.UrlReferrer != null)
            {
                TempData["backUrl"] = Request.UrlReferrer.ToString();
                ViewBag.backUrl = Request.UrlReferrer.ToString();
            }
            else
            {
                ViewBag.backUrl = Url.Action("Index");
            }

            AudioModel model = new AudioModel(albumID ?? default(int));
            AudioInfo audio = model.Get(id ?? default(int));
            if (audio == null)
                return RedirectToAction("Index");


            return View(audio);
        }

        [HttpPost]
        public ActionResult Edit(AudioInfo audio, HttpPostedFileBase file, HttpPostedFileBase thummnail, int albumID)
        {
            ViewBag.backUrl = TempData["backUrl"];
            TempData.Keep();
            if (ModelState.IsValid)
            {
                try
                {
                    AudioModel model = new AudioModel(albumID);
                    if (FileValidation.IsValid(file, new List<string>(){
                            ".aac", ".m4v", ".m4a", ".mp1", ".mp2", ".mp3", ".mpg", ".mpeg", ".oga", ".ogg", ".wav", ".webm"
                    }))
                    {
                        model.Update(audio, file, thummnail);
                    }
                    return RedirectToAction("Index");
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("", "Error editing record. " + ex.Message);
                }
            }

            return View(audio);
        }

        public ActionResult Delete(int? id, int? albumID)
        {
            if (!albumID.HasValue)
            {
                return RedirectToAction("Index", "Albums");
            }
            if (!id.HasValue)
            {
                return RedirectToAction("Index");
            }
            TempData["backUrl"] = Request.UrlReferrer.ToString();
            ViewBag.backUrl = Request.UrlReferrer.ToString();

            AudioModel model = new AudioModel(albumID ?? default(int));
            AudioInfo audio = model.Get(id ?? default(int));
            if (audio == null)
                return RedirectToAction("Index");

            return View(audio);
        }

        [HttpPost]
        public ActionResult Delete(int albumID, AudioInfo audio)
        {
            ViewBag.backUrl = TempData["backUrl"];
            TempData.Keep();
            AudioModel model = new AudioModel(albumID);

            try
            {
                model.Delete(audio);
                return RedirectToAction("Index");
            }
            catch (Exception ex)
            {
                ViewBag.ErrorMsg = "Error deleting record. " + ex.Message;
                return View(audio);
            }
        }

        public ViewResult Play(int? id, int? albumId)
        {
            ViewBag.AlbumID = albumId;
            AudioModel model = new AudioModel(albumId ?? default(int));
            AudioViewModel viewModel = new AudioViewModel();
            viewModel.Audio = model.Get(id ?? 1);
            viewModel.AudioList = model.Get();
            return View(viewModel);
        }

        public ActionResult List(int? albumID, int? page)
        {
            AudioModel model = new AudioModel(albumID ?? default(int));
            var products = model.Get();

            var pageNumber = page ?? 1;
            var onePageOfProducts = products.ToPagedList(pageNumber, Tune.ItemsPerPage);

            ViewBag.OnePageOfProducts = onePageOfProducts;
            return View(model.Get());
        }

        public ActionResult Download(string file = "")
        {

            var fileStream = new FileStream(file, FileMode.Open, FileAccess.ReadWrite);
            var mimeType = "audio/mpeg";
            var fileDownloadName = Path.GetFileName(file);
            return File(fileStream, mimeType, fileDownloadName);
        }
    }
}
